import 'dart:convert';
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:namewava/utils/jc_cache.dart';

typedef Success<T> = Function(T data);
typedef Fail = Function(String msg);

class JcHttpUtils {
  final Dio _dio = Dio(BaseOptions(
      connectTimeout: const Duration(milliseconds: 5000),
      receiveTimeout: const Duration(milliseconds: 5000)));

  getReques(String url, var parms,
      {required Success success,
      bool isNeedToken = true,
      bool isJson = true}) async {
    // http.get(url)
    _dio.options.headers = _getHeaders();
    if (isNeedToken) {
      _dio.options.headers['Authorization'] = 'Bearer ${_getToken()}';
    } else {
      _dio.options.headers.remove('Authorization');
    }

    if (isJson) {
      _dio.options.headers['Content-Type'] = Headers.jsonContentType;
    } else {
      _dio.options.headers['Content-Type'] = Headers.formUrlEncodedContentType;
    }

    try {
      var res = await _dio.get(url, queryParameters: parms);
      var data = res.data;
      log(url);
      log(data.toString());
      if (data != null) {
        _successRequesData(data, success);
      } else {
        EasyLoading.dismiss();
        EasyLoading.showError('Request failure');
      }
    } on DioException catch (e) {
      log(e.toString());
      EasyLoading.dismiss();
      EasyLoading.showError('Request failure');
    }
  }

  postReques(String url, var parms,
      {required Success success,
      bool isNeedToken = true,
      bool isJson = true}) async {
    // http.get(url)
    _dio.options.headers = _getHeaders();
    if (isNeedToken) {
      _dio.options.headers['Authorization'] = 'Bearer ${_getToken()}';
    } else {
      _dio.options.headers.remove('Authorization');
    }

    if (isJson) {
      _dio.options.headers['Content-Type'] = Headers.jsonContentType;
    } else {
      _dio.options.headers['Content-Type'] = Headers.formUrlEncodedContentType;
    }

    try {
      var res = await _dio.post(
        url,
        data: parms,
      );
      // if (isNeedToken) {
      //   res = await _dio.post(url,
      //       data: parms,
      //       options: Options(method: 'post', headers: {
      //         HttpHeaders.authorizationHeader: 'Bearer ${_getToken()}'
      //       }));
      // } else {
      //   res = await _dio.post(
      //     url,
      //     data: parms,
      //   );
      // }
      var data = res.data;
      log(url);
      log(data.toString());
      if (data != null) {
        _successRequesData(data, success);
      } else {
        EasyLoading.dismiss();
        EasyLoading.showError('Request failure');
      }
    } on DioException catch (e) {
      log(e.toString());
      EasyLoading.dismiss();
      EasyLoading.showError('Request failure');
    }
  }

  postLogReques(String url, var parms,
      {required Success success,
      bool isNeedToken = true,
      bool isJson = true}) async {
    // http.get(url)
    _dio.options.headers = parms;
    _dio.options.headers['Content-Type'] = Headers.jsonContentType;

    try {
      var res = await _dio.post(
        url,
        data: [parms],
      );
      var data = res.data;
      log(url);
      log('日志上报结果：${data.toString()}');
    } on DioException catch (e) {
      log(e.toString());
    }
  }

  // _failRequest(DioException error) {}

  _successRequesData(var data, Success s) {
    if (data is Map) {
      var code = data['code'];
      if (code == 10010301 ||
          code == 10010302 ||
          code == 10010303 ||
          code == 100103) {
        EasyLoading.dismiss();
        EasyLoading.showInfo('Login expired, please log in again');
      } else if (code == 0) {
        s(data);
      } else {
        EasyLoading.dismiss();
        EasyLoading.showError(data['msg']);
      }
    } else if (data is String) {
    } else {}
  }

  _getHeaders() {
    String appinfo = JcCache.getInstance().get('appinfo');
    Map<String, dynamic> headers = {};
    if (appinfo.isNotEmpty) {
      headers = jsonDecode(appinfo);
    }
    headers['Accept'] = 'application/json';
    return headers;
  }

  _getToken() {
    var token = JcCache.getInstance().get('wavaToken');
    token = token ?? '';
    return token;
  }
}
